document.addEventListener('DOMContentLoaded', function () {
    const contactForm = document.getElementById("contactForm");
    const errorMessages = {
        name: "请输入您的姓名",
        email: "请输入有效的邮箱地址",
        phone: "请输入联系电话",
        message: "请输入留言内容",
    };
    // 初始化输入框事件
    document.querySelectorAll(".form-control").forEach((input) => {
        input.addEventListener("input", function () {
            this.classList.remove("error");
            const errorDiv = this.parentElement.querySelector(".error-msg");
            errorDiv.classList.remove("show");
        });
    });
    const successDiv = document.getElementById("success");
    const errorDiv = document.getElementById("error");
    let successTimer = null;
    let errorTimer = null;
    // 初始化提示框状态
    successDiv.style.display = "none";
    errorDiv.style.display = "none";

    function showError(inputElement, message) {
        inputElement.classList.add("error");
        const errorDiv = inputElement.parentElement.querySelector(".error-msg");
        errorDiv.textContent = message;
        errorDiv.classList.add("show");
    }

    function showSuccessMessage(msg) {
        const successDiv = document.getElementById("success");
        successDiv.textContent = msg;
        successDiv.style.display = "block";
        setTimeout(() => (successDiv.style.display = "none"), 3000);
    }

    // 显示错误提示的函数示例
    function showErrorMessage(msg) {
        const errorDiv = document.getElementById("error");
        errorDiv.textContent = msg;
        errorDiv.style.display = "block";
        setTimeout(() => (errorDiv.style.display = "none"), 3000);
    }
    // 自动隐藏函数
    function autoHide(element, timerVar) {
        if (timerVar) clearTimeout(timerVar);
        return setTimeout(() => {
            element.style.display = "none";
        }, 3000); // 3秒后自动隐藏
    }

    contactForm.addEventListener("submit", function (e) {
        e.preventDefault();
        let isValid = true;
        // 清除所有错误状态
        document.querySelectorAll(".form-control").forEach((input) => {
            input.classList.remove("error");
        });
        document.querySelectorAll(".error-msg").forEach((div) => {
            div.classList.remove("show");
        });
        // 验证姓名
        const nameInput = document.getElementById("name");
        if (!nameInput.value.trim()) {
            showError(nameInput, errorMessages.name);
            isValid = false;
        }

        // 验证邮箱
        const emailInput = document.getElementById("email");
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailInput.value.trim()) {
            showError(emailInput, errorMessages.email);
            isValid = false;
        } else if (!emailRegex.test(emailInput.value)) {
            showError(emailInput, "邮箱格式不正确");
            isValid = false;
        }

        // 验证电话
        const phoneInput = document.getElementById("phone");
        if (!phoneInput.value.trim()) {
            showError(phoneInput, errorMessages.phone);
            isValid = false;
        }

        // 验证留言
        const messageInput = document.getElementById("message");
        if (!messageInput.value.trim()) {
            showError(messageInput, errorMessages.message);
            isValid = false;
        }

        if (!isValid) return;
        // 清除之前的提示和计时器
        successDiv.style.display = "none";
        errorDiv.style.display = "none";
        if (successTimer) clearTimeout(successTimer);
        if (errorTimer) clearTimeout(errorTimer);
        // 表单验证
        const name = document.getElementById("name").value.trim();
        const email = document.getElementById("email").value.trim();
        const phone = document.getElementById("phone").value.trim();
        const message = document.getElementById("message").value.trim();
        if (!name || !email || !phone || !message) {
            errorDiv.style.display = "block";
            errorTimer = autoHide(errorDiv, errorTimer);
            return;
        }
        // 创建 FormData 对象
        const formData = new FormData(this);

        // 发送 AJAX 请求
        fetch("index/contactProcess", {
            method: "POST",
            body: formData,
        })
            .then((response) => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                // 根据响应内容类型解析数据
                const contentType = response.headers.get("content-type");
                if (contentType && contentType.includes("application/json")) {
                    return response.json(); // 解析JSON数据
                } else {
                    return response.text(); // 解析文本数据
                }
                // if (response.ok) {
                //   // 提交成功后处理
                //   contactForm.reset();
                //   successDiv.style.display = "block";
                //   successTimer = autoHide(successDiv, successTimer);
                // } else {
                //   errorDiv.style.display = "block";
                //   errorTimer = autoHide(errorDiv, errorTimer);
                // }
            })
            .then((data) => {
                // 处理服务端返回的数据
                if (data.code === 1) {
                    contactForm.reset();
                    showSuccessMessage(data.msg || "提交成功！");
                } else {
                    showErrorMessage(data.msg || "提交失败，请重试");
                }
            })
            .catch((error) => {
                console.error("Error:", error);
                errorDiv.style.display = "block";
                errorTimer = autoHide(errorDiv, errorTimer);
            });
    });
})